#include "crossplatform.h"

#ifdef WIN32
struct WindowsThreadSpawnInfo
{
	WindowsThreadSpawnInfo(void* (*cb)(void*), void *p) : CB(cb), Arg(p) {}

	void* (*CB)(void*);
	void *Arg;
};
static DWORD CALLBACK ThreadStart(void *arg)
{
	WindowsThreadSpawnInfo *info = (WindowsThreadSpawnInfo*)arg;
	void* (*CB)(void*) = info->CB;
	void *param = info->Arg;
	delete info;
	return (DWORD)(size_t)CB(param);
}
bool SpawnThread(void* (*fn)(void*), void *arg, pthread_t *thread)
{
	HANDLE h = CreateThread(NULL, 0, ThreadStart, new WindowsThreadSpawnInfo(fn, arg), 0, 0);
	if(h == NULL || h == INVALID_HANDLE_VALUE) {
		if(thread)
			*thread = NULL;
		return false;
	}

	if(thread)
		*thread = h;
	else
		CloseHandle(h);
	return true;
}

void* JoinThread(pthread_t h)
{
	if(!h)
		return NULL;

	DWORD code;
	WaitForSingleObject(h, INFINITE);
	GetExitCodeThread(h, &code);
	CloseHandle(h);
	return (void*)(size_t)code;
}
#endif
